<template>
	<view class="search-suggestions-page">
		<view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="search-bar">
				<u-icon name="arrow-left" size="20" color="#303133" @click="navigateBack"></u-icon>
				<view class="search-input-container">
					<u-icon name="search" color="#c0c4cc" size="18"></u-icon>
					<input class="search-input" type="text" v-model="keyword" placeholder="城市·景点" confirm-type="search"
						:focus="isInputFocused" @confirm="performSearch" @input="handleInputChange" />
				</view>
				<text class="search-button" @click="performSearch">搜索</text>
			</view>
		</view>

		<scroll-view scroll-y class="content-scroll" :style="{ paddingTop: headerHeight + 'px' }">
			<!-- 搜索历史 -->
			<view class="section search-history" v-if="searchHistory.length > 0">
				<view class="section-header">
					<text class="section-title">搜索历史</text>
					<u-icon name="trash" size="20" color="#909399" @click="confirmClearHistory"></u-icon>
				</view>
				<view class="history-tags">
					<view class="history-tag-item" v-for="(item, index) in displayedHistory" :key="index"
						@click="selectHistory(item)">
						{{ item }}
					</view>
					<view class="history-tag-item expand-button"
						v-if="searchHistory.length > initialHistoryDisplayCount" @click="toggleHistoryExpansion">
						<u-icon :name="historyExpanded ? 'arrow-up' : 'arrow-down'" size="14" color="#606266"></u-icon>
					</view>
				</view>
			</view>

			<!-- 猜你想搜 -->
			<view class="section guess-you-like">
				<view class="section-header">
					<text class="section-title">猜你想搜</text>
					<view class="refresh-button" @click="refreshGuessItems">
						<u-icon name="reload" size="18" color="#909399"></u-icon>
					</view>
				</view>
				<view class="guess-items-grid">
					<view class="guess-item" v-for="(item, index) in guessItems" :key="index"
						@click="selectGuess(item)">
						{{ item }}
					</view>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view class="section hot-searches">
				<view class="section-header section-rmss">
					<!-- <image src="@/static/index/icon_hot.png" class="hot-icon" mode="widthFix"></image> -->
					<text class="section-title hot-title">热门搜索</text>
				</view>
				<view class="hot-list">
					<view class="hot-item" v-for="(item, index) in hotSearches" :key="index"
						@click="selectHotSearch(item.title)">
						<text :class="getRankClass(index + 1)+' hot-rank'">{{ index + 1 }}</text>
						<text class="hot-text">{{ item.title }}</text>
						<text class="hot-participants" v-if="item.participants">已有{{ item.participants }}+人参与</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	const SEARCH_HISTORY_KEY = 'home_search_history';
	const MAX_HISTORY_COUNT = 20;
	const INITIAL_HISTORY_DISPLAY_COUNT = 5; // 初始显示的搜索历史数量

	export default {
		data() {
			return {
				statusBarHeight: 0,
				headerHeight: 0, // 用于scroll-view的padding-top
				keyword: '',
				isInputFocused: false,
				searchHistory: [],
				historyExpanded: false,
				initialHistoryDisplayCount: INITIAL_HISTORY_DISPLAY_COUNT,
				guessItems: [
					'大英博物馆文创火了', '敦煌莫高窟临时关闭',
					'淮安府署剧本杀', '西沙海底墓',
					'北京环球影城', '南京牛首山文化旅游区'
				],
				// 模拟的热门搜索数据
				hotSearches: [{
						title: '探秘突然爆火的炙羊山',
						participants: '654120'
					},
					{
						title: '被火山喷发掩埋的庞贝古城在哪儿',
						participants: '565120'
					},
					{
						title: '跟着《滕王阁序》游江西',
						participants: '399999'
					},
					{
						title: '跟着课本游中国，知行合一',
						participants: '235120'
					},
					{
						title: '特种兵旅游，高效打卡',
						participants: '125118'
					},
					{
						title: '旅游中的city 不 city 热梗',
						participants: '95123'
					},
					{
						title: '年轻人爱收集的旅游冰箱贴',
						participants: '55291'
					},
					{
						title: '因麻辣烫爆火的天水旅游',
						participants: '31230'
					},
					{
						title: '阿勒泰旅游因电视剧出圈',
						participants: '11691'
					},
					{
						title: '奥运会冠军家乡旅游热潮',
						participants: '5184'
					},
				],
				allGuessItemsPool: [ // 用于刷新“猜你想搜”
					'大英博物馆文创火了', '敦煌莫高窟临时关闭', '淮安府署剧本杀', '西沙海底墓',
					'北京环球影城', '南京牛首山文化旅游区', '上海迪士尼乐园攻略', '成都大熊猫繁育研究基地',
					'西安兵马俑', '杭州西湖十景', '厦门鼓浪屿', '三亚蜈支洲岛', '重庆洪崖洞夜景',
					'云南丽江古城', '桂林山水甲天下', '张家界国家森林公园'
				],
			};
		},
		computed: {
			displayedHistory() {
				if (this.historyExpanded) {
					return this.searchHistory;
				}
				return this.searchHistory.slice(0, this.initialHistoryDisplayCount);
			}
		},
		onLoad(options) {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;

			// 动态获取顶部固定区域高度
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.fixed-header').boundingClientRect(data => {
					if (data) {
						this.headerHeight = data.height;
					}
				}).exec();
			});

			this.loadSearchHistory();
			if (options.keyword) {
				this.keyword = decodeURIComponent(options.keyword);
			}
		},
		onShow() {
			// 尝试在页面显示时聚焦输入框
			setTimeout(() => {
				this.isInputFocused = true;
			}, 150);
		},
		methods: {
			navigateBack() {
				uni.navigateBack();
			},
			handleInputChange(e) {
				// 可以在这里添加输入时的联想建议逻辑 (如果需要)
			},
			performSearch() {
				this.isInputFocused = false; // 触发搜索时可以失焦
				const searchTerm = this.keyword.trim();
				if (searchTerm) {
					this.addSearchHistory(searchTerm);
					// 执行实际的搜索逻辑，例如跳转到搜索结果页
					uni.navigateTo({
						url: `/pages_sub/common/search-suggestions/search-detail?keyword=${encodeURIComponent(searchTerm)}`
					})

				} else {
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					});
				}
			},
			loadSearchHistory() {
				const history = uni.getStorageSync(SEARCH_HISTORY_KEY);
				if (history && Array.isArray(history)) {
					this.searchHistory = history;
				}
			},
			addSearchHistory(term) {
				let history = [...this.searchHistory];
				// 移除已存在的相同记录，将其移到最前
				history = history.filter(item => item !== term);
				history.unshift(term);
				// 保持最大数量
				if (history.length > MAX_HISTORY_COUNT) {
					history = history.slice(0, MAX_HISTORY_COUNT);
				}
				this.searchHistory = history;
				uni.setStorageSync(SEARCH_HISTORY_KEY, history);
			},
			confirmClearHistory() {
				if (this.searchHistory.length === 0) return;
				uni.showModal({
					title: '提示',
					content: '确定要清空所有搜索历史吗？',
					success: (res) => {
						if (res.confirm) {
							this.clearSearchHistory();
						}
					}
				});
			},
			clearSearchHistory() {
				this.searchHistory = [];
				uni.removeStorageSync(SEARCH_HISTORY_KEY);
			},
			selectHistory(term) {
				this.keyword = term;
				this.performSearch();
			},
			toggleHistoryExpansion() {
				this.historyExpanded = !this.historyExpanded;
			},
			refreshGuessItems() {
				// 模拟从更多数据中随机抽取
				let shuffled = [...this.allGuessItemsPool].sort(() => 0.5 - Math.random());
				this.guessItems = shuffled.slice(0, 6); // 假设总是显示6个
				uni.showToast({
					title: '已为你更新推荐',
					icon: 'none',
					duration: 1000
				});
			},
			selectGuess(term) {
				this.keyword = term;
				this.performSearch();
			},
			selectHotSearch(term) {
				this.keyword = term;
				this.performSearch();
			},
			getRankClass(rank) {
				if (rank >= 1 && rank <= 3) {
					return 'rank-top3';
				}
				return 'rank-other';
			}
		},
	};
</script>

<style lang="scss" scoped>
	.search-suggestions-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #ffffff;
	}

	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		z-index: 100;
		border-bottom: 1rpx solid #f0f0f0;

		.search-bar {
			display: flex;
			align-items: center;
			height: 44px; // 与标准导航栏内容区同高
			padding: 0 24rpx;

			.search-input-container {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #f4f4f4;
				border-radius: 30rpx;
				height: 64rpx;
				padding: 0 20rpx;
				margin: 0 20rpx;

				.search-input {
					flex: 1;
					font-size: 28rpx;
					color: #303133;
					margin-left: 10rpx;
					height: 100%;
				}
			}

			.search-button {
				font-size: 30rpx;
				color: #303133;
			}
		}
	}

	.content-scroll {
		flex: 1;
		background-color: #ffffff;
	}

	.section {
		padding: 30rpx 30rpx 0;
		margin-bottom: 20rpx; // 各个区域之间的间距
	}

	.section:last-child {
		margin-bottom: 0 !important;
	}

	.section-rmss {
		justify-content: flex-start !important;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;

		.section-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #303133;
		}

		.hot-icon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 8rpx;
		}

		.hot-title {
			color: #FF2B22; // 热门搜索标题红色
		}

		.refresh-button {
			padding: 4rpx; // 增加点击区域
		}
	}

	.search-history {
		.history-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;

			.history-tag-item {
				background-color: #f4f4f4;
				color: #303133;
				font-size: 26rpx;
				padding: 10rpx 20rpx;
				border-radius: 24rpx;
				display: flex;
				align-items: center;
			}

			.expand-button {
				background-color: transparent; // 或者与tag一致
				// border: 1rpx solid #e0e0e0; // 可选边框
			}
		}
	}

	.guess-you-like {
		.guess-items-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr); // 两列
			gap: 20rpx; // 间距

			.guess-item {
				font-size: 28rpx;
				color: #303133;
				padding: 16rpx 0; // 上下间距
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				// background-color: #f9f9f9; // 可选的背景色
				// border-radius: 8rpx;
				// text-align: center;
			}
		}
	}

	.hot-searches {
		padding-bottom: 20rpx;

		.hot-list {
			.hot-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				font-size: 28rpx;
				color: #303133;
				border-bottom: 1rpx solid #f5f5f5;

				&:last-child {
					border-bottom: none;
				}

				.hot-rank {
					width: 36rpx; // 固定宽度以对齐
					font-weight: bold;
					margin-right: 16rpx;
					text-align: center;

					&.rank-top3 {
						color: #FF2B22; // 前三名红色
					}

					&.rank-other {
						color: #FF8C00; // 其他名次橙色
					}
				}

				.hot-text {
					flex: 1;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.hot-participants {
					font-size: 24rpx;
					color: #909399;
					margin-left: 20rpx;
					white-space: nowrap;
				}
			}
		}
	}
</style>